import Vue from 'vue';
import GoEasy from '@/uni_modules/GOEASY-IM/js_sdk/goeasy-2.6.1.esm.min.js'
const app_info = require("@/common/appInfo.js");
const api_host = app_info.api_host
import store from '../store/index.js'
import {
	wxLogin,
	userLike
} from './api_user.js'

module.exports = {

	/**
	 * 微信登录
	 * @returns {Promise<*>}
	 */
	async wxLogin() {
		const that = this
		uni.login({
			provider: 'weixin',
			success: async loginRes => {
				console.log(loginRes, 'loginRes');
				let code = loginRes.code
				uni.showLoading()
				const res = await wxLogin({
					code
				})
				if (res.code == 200) {
					uni.setStorageSync('token', res.data.token)
					await store.dispatch('getUserinfo')
					Vue.prototype.$isResolve()
					uni.hideLoading()
				}
			}
		});
	},
	//点赞收藏
	userLike(operation, busine, speId) {
		return new Promise(async (resolve, reject) => {
			const res = await userLike({
				operation,
				busine,
				speId
			})
			if (res.code == 200) {
				resolve({
					code: 200,
					msg: operation == 1 ? '收藏成功' : '点赞成功'
				})
			}
		})
	},
	//预览图片
	previewImages(index, imgs) {
		let data = imgs;
		let arr = [];
		data.forEach(item => {
			arr.push(api_host + item)
		})
		console.log(arr);
		uni.previewImage({
			urls: arr,
			current: index
		})
	},
	// 手机号校验
	validatePhone(phone) {
	  const reg = /^1[3-9]\d{9}$/;
	  return reg.test(phone);
	},
	// 校验邮箱
	validateEmail(email){ 
		var reg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
		return reg.test(email);
	},
	// 身份号码脱敏
	maskedIdCard (val) {
	   let reg = /^(.{3})(?:\d+)(.{4})$/    // 匹配身份证号前3位和后3位的正则表达式
	   if (val) {
	       return val.replace(reg, '\$1***********\$2')
	   }
	},
	// 姓名加密
	maskedName(name){
		return name.replace(/(^.).*/, '$1*');
	},
	// 根据经纬度算距离
	getDistance(locallatitude,locallongitude,latitude,longitude) {
		if(!locallatitude || !locallongitude){
			return '位置获取失败'
		}
	    let R = 6371000; // 地球平均半径，单位：米
	    let lat1 = locallatitude * Math.PI / 180;
	    let lat2 = latitude * Math.PI / 180;
	    let lon1 = locallongitude * Math.PI / 180;
	    let lon2 = longitude * Math.PI / 180;
	    let a = Math.sin((lat2 - lat1) / 2) * Math.sin((lat2 - lat1) / 2) +
	            Math.cos(lat1) * Math.cos(lat2) * Math.sin((lon2 - lon1) / 2) * Math.sin((lon2 - lon1) / 2);
	    let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	    let d = R * c; // 初始计算得到的距离，单位：米
	 
	    if (d >= 1000) {
	        // 如果距离大于等于1000米（即1千米），则换算为千米并保留两位小数
	        return (d / 1000).toFixed(2) + "km";
	    } else {
	        return d.toFixed(0) + "m";
	    }
	},
	/**
	 * 上传文件
	 * @returns {Promise<*>}
	 */
	uploadFile(filePath, showLoading = true) {

		if (showLoading) {
			uni.showLoading({
				title: '上传中..',
				mask: true
			})
		}

		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: api_host + '/common/upload',
				filePath: filePath,
				name: 'file',
				success: (res) => {
					let data = JSON.parse(res.data)
					if (data.code == 200) {
						data.full_url = data.fileName
						resolve(data)
					} else {
						resolve(data)
						uni.showModal({
							title: '提示',
							content: data.msg,
							showCancel: false
						})
					}
				},
				fail: (res) => {
					reject(res)
				},
				complete: (res => {
					showLoading && uni.hideLoading()
				})
			})
		})
	},
	//根据时间戳计算星期几
	getWeek(times) {
		let date = new Date(times)
		let day = date.getDay()
		return day
	},
	//获取当前日期函数
	getNowFormatDate() {
		let date = new Date(),
			year = date.getFullYear(), //获取完整的年份(4位)
			month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
			strDate = date.getDate() // 获取当前日(1-31)
		if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
		if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0

		return `${year}-${month}-${strDate}`
	},

	//将数字转换成万 并且保留两位小数
	keepTwoDecimalFull(num) {
		if (num > 10000) {
			let result = num / 10000;
			result = Math.floor(result * 100) / 100;
			var s_x = result.toString(); //将数字转换为字符串
			var pos_decimal = s_x.indexOf('.'); //小数点的索引值
			// 当整数时，pos_decimal=-1 自动补0
			if (pos_decimal < 0) {
				pos_decimal = s_x.length;
				s_x += '.';
			}
			// 当数字的长度< 小数点索引+2时，补0
			while (s_x.length <= pos_decimal + 2) {
				s_x += '0';
			}
			s_x += '万';
		} else {
			s_x = num;
		}
		return s_x
	},
	//链接goeasy
	connectGoEasy(userInfo) {
		const goEasy = GoEasy.getInstance({
			host: app_info.goEasy.host, //应用所在的区域地址: [hangzhou.goeasy.io, 新加坡暂不支持IM，敬请期待]
			appkey: app_info.goEasy.appkey, // common key,
			modules: ['im'],
			// true表示支持通知栏提醒，false则表示不需要通知栏提醒
			allowNotification: false //仅有效于app,小程序和H5将会被自动忽略
		});
		uni.showLoading();
		goEasy.connect({
			id: userInfo.id,
			data: {
				name: userInfo.userName,
				avatar: userInfo.userAvatar
			},
			onSuccess: () => {
				console.log('GoEasy connect successfully.')
			},
			onFailed: (error) => {
				console.log('Failed to connect GoEasy, code:' + error.code + ',error:' + error.content);
			},
			onProgress: (attempts) => {
				console.log('GoEasy is connecting', attempts);
			}
		});
		uni.hideLoading()
	},
	//订阅消息
	async messageSubscriptionAuthorization(tmplIds) {
		return new Promise((resolve, reject) => {
			uni.getSetting({
				withSubscriptions: true,
				success(res) {
					let info = res.subscriptionsSetting;
					let isFirst = true; // 是否第一次授权
					if (info.itemSettings) {
						tmplIds.forEach((item) => {
							if (info.itemSettings[item] == 'accept') {
								isFirst = false;
							}
						});
					}
					console.log('订阅信息设置', info);
					if (!info.mainSwitch) {
						uni.openSetting({
							//打开设置页
							success(res) {
								console.log('打开设置页', res.authSetting);
							},
						});
					} else {
						uni.requestSubscribeMessage({
							tmplIds,
							success(res) {
								console.log('订阅信息', res);
								let isTmplId = true; // 是否全部授权成功
								let temIds = []
								tmplIds.forEach((item) => {
									if (res[item] != 'accept') {
										isTmplId = false;
									}
									if (res[item] == 'accept') {
										temIds.push(item)
									}
								});
								resolve({
									temIds,
									result: isTmplId,
									isTip: isFirst,
									msg: isTmplId ? '消息订阅授权成功' : '消息订阅未授权',
								});
							},
							fail(errMessage) {
								console.log('订阅消息 失败 ', errMessage);
								resolve({
									result: false,
									isTip: isFirst,
									msg: '订阅消息失败'
								});
							},
						});
					}
				},
			});
		});
	}
}